package cn.bj.yu.add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author 周宇
 * @create 2020-08-13 12:06
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 线程数量 停车位! 限流！
        Semaphore semaphore = new Semaphore(10);

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();// acquire 得到
                    System.out.println(Thread.currentThread().getName() + " 抢到车位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + " 离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();// 释放这个位置
                }
            }, String.valueOf(i)).start();
        }
    }
}
